﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using Autodesk.RevitAddIns;

namespace RevitStarter
{
    using RevitStarter.Util;

    public partial class StarForm : Form
    {
        private readonly string m_addInName;
        private readonly string m_iconName;
        private readonly string m_titleName;
        private readonly string m_pictureName;
        private readonly List<RevitProduct> m_revitProducts;


        public StarForm(List<RevitProduct> revitList, string iconName, string titleName, string pictureName, string addInName)
        {
            m_revitProducts = revitList;
            m_iconName = iconName;
            m_titleName = titleName;
            m_pictureName = pictureName;
            m_addInName = addInName;

            InitializeComponent();
        }

        private void StarForm_Load(object sender, EventArgs e)
        {
            Text = m_titleName;

            string imgPath = Path.Combine(Application.StartupPath, m_pictureName);
            if (File.Exists(imgPath))
            {
                picBanner.ImageLocation = imgPath;
            }

            string iconPath = Path.Combine(Application.StartupPath, m_iconName);
            if (File.Exists(iconPath))
            {
                Icon = new Icon(iconPath);
            }

            Debug.Assert(m_revitProducts.Count != 0);

            RevitListCtrl.DataSource = m_revitProducts;
            RevitListCtrl.DisplayMember = "Version";
            RevitListCtrl.SelectedItem = RevitListCtrl.Items[0];

            //#ToDo 暂不进行参数记忆
        }

        private void btnStartRevit_Click(object sender, EventArgs e)
        {
            if (RevitListCtrl.SelectedItem == null)
            {
                UiUtil.InformationMessageBox("请选择需要启动的Revit版本！");
                return;
            }

            RevitProduct selItem = (RevitProduct) RevitListCtrl.SelectedItem;
            if (AddinUtil.UpdateAddInFile(selItem, m_addInName))
            {
                Process.Start(Path.Combine(selItem.InstallLocation, "Revit.exe"));
                Thread.Sleep(1000); //暂停一秒再隐藏

                DialogResult = DialogResult.OK;
                Close();
            }
            else
            {
                DialogResult = DialogResult.Cancel;
                Close();
            }
        }


        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}